package com.fishing.filter;

import com.fishing.entity.Admin;
import com.fishing.keyrun.KeyManager;
import com.fishing.util.Constants;
import com.fishing.util.RSAUtil;
import com.fishing.util.SysUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

public class LoginFilter implements Filter {
	private Log log = LogFactory.getLog(LoginFilter.class);

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) srequest;
		HttpServletResponse response = (HttpServletResponse) sresponse;
		response.setCharacterEncoding("UTF-8");
		String path = request.getServletPath();
		if (path.equals("/login") || path.equals("/imageCode") || path.equals("/loginDo") || path.startsWith("/publickey") || path.startsWith("/css/")
				|| path.startsWith("/fonts/") || path.startsWith("/img/")
				|| path.startsWith("/js/") || path.startsWith("/i/") || path.startsWith("/layui/")) {
			log.debug("请求资源：" + path + "通过");
			//把请求传回过滤链
			chain.doFilter(request, response);
		} else {
			HttpSession session = request.getSession();
			//检查当前 session  Admin是否为空，如果为空，需要跳转到登录页面
			Admin admin = (Admin) session.getAttribute(Constants.loginKey);
			if (admin == null) {
				log.debug("当前无用户登录..");
				if (isAjaxRequest(request)) {
					log.debug("当前request为ajax方式..");

					Map<String, Object> obj = new HashMap<String, Object>();
					obj.put("logout", true);
					obj.put("message", "登录失效，请重新登录！");
					obj.put("view", SysUtil.getBasePath(request) + "login");
					PrintWriter out = response.getWriter();
					//out.print(SysUtil.convertJsonStrToObj(obj));
				} else {
					log.debug("当前request为非ajax方式..");
					PrintWriter out = response.getWriter();
					response.sendRedirect(SysUtil.getBasePath(request) + "login");
				}
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	/***
	 * 判断是否有权限
	 * 
	 * @param session
	 * @param serviceView
	 * @return
	 */
	public boolean hasRight(HttpSession session, String serviceView) {
		return false;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
        String site = config.getInitParameter("Site");
        System.out.println("打开网站: " + site);
        // 生成秘钥对
        KeyPair keyPair;
		try {
			keyPair = RSAUtil.getKeyPair();
			// 获取私钥
			String private_key = RSAUtil.getPrivateKey(keyPair);
			// 获取公钥
			String public_key = RSAUtil.getPublicKey(keyPair);
			// 设置私钥
			KeyManager.setPrivate_key(private_key);
			// 设置公钥
			KeyManager.setPublic_key(public_key);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/***
	 * 判断当前请求是否ajax请求
	 * 
	 * @param request HttpServletRequest对象
	 * @return true：是，false：否
	 */
	public boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header)) {
			return true;
		}
		return false;
	}

}
